/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2015年1月27日         cassie
 */

package com.tianci.appstore.ui.list.bootsetting;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSONObject;
import com.coocaa.app.gamecenter.pages.home.GameMainActivity;
import com.coocaa.launcher.EasyLauncherActivity;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.AsyncTask;
import com.coocaa.x.framework.utils.LiteURI;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.litecontent.LiteContentServiceConnecter;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.AppData;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.RP_Installed_Apps;
import com.coocaa.x.service.litepm.data.MActivityInfo;
import com.skyworth.framework.skysdk.properties.SkyGeneralProperties;
import com.tianci.appstore.AppStoreActivity;
import com.tianci.appstore.R;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.data.SkyListSwitchData;
import com.tianci.appstore.ui.list.ListFlipper;
import com.tianci.appstore.ui.list.ListSwitchBlock;
import com.tianci.appstore.ui.list.SkyListAdapter;
import com.tianci.appstore.ui.list.bootsetting.AppSelectedData.AppItem;
import com.tianci.appstore.ui.list.manage.ManageBaseListView;
import com.tianci.appstore.ui.list.manage.ManageListController;
import com.tianci.appstore.ui.widget.SkyAppPager.Direction;
import com.tianci.appstore.ui.widget.SkyCustomLayout;
import com.tianci.appstore.ui.widget.SkyCustomLayout.BlockData;
import com.tianci.appstore.ui.widget.SkyCustomLayout.CustomLayoutParams;
import com.tianci.appstore.utils.SkyConstants;

import java.util.ArrayList;
import java.util.List;

public class SelectLaunchListView extends ManageBaseListView {
    private static final String HOMEPKG = "com.coocaa.homeshell";
    private static final String SYSTEMPKG = "com.tianci.system";
    private List<SkyListSwitchData> dataList;

    public SelectLaunchListView(Context context) {
        super(context, ListType.SELECTED_LAUNCH_LIST);
        setLoadingVisible(true);
        getData();
    }

    private void getData() {
        AsyncTask.runOnThread(new Runnable() {
            @Override
            public void run() {
                try {
//                    String result = LiteContentServiceConnecter.getService().call(
//                            "apps://com.coocaa.app/installed_apps?action=get");
                    LiteURI uri = LiteURI.create("apps://com.coocaa.app/installed_apps");
                    uri.addParams("filter", "autostart");
                    String result = LiteContentServiceConnecter.getService().call(uri.toString());
                    String currentLauncher = LiteContentServiceConnecter.getService().call(
                            "setting://com.coocaa.launcher/current_launcher?action=get");
                    List<SkyListAppData> appDatas = new ArrayList<SkyListAppData>();
                    SkyListAppData empty = new SkyListAppData("", "", "", "", "");
                    empty.setMainActivity("");
                    AppItem currentItem = null;
                    if (currentLauncher != null) {
                        AppSelectedData current = JSONObject.parseObject(currentLauncher,
                                AppSelectedData.class);
                        if (current != null && current.error_code == 0 && current.resource != null
                                && current.resource.total_count > 0) {
                            currentItem = current.resource.resource_items.get(0);
                        }
                    }
                    int settingCode = 0;
                    try {
                        settingCode = CoocaaApplication.getContext().getPackageManager().getPackageInfo(SYSTEMPKG, 0).versionCode;
                    } catch (PackageManager.NameNotFoundException e) {
                        settingCode = 0;
                        e.printStackTrace();
                    }
                    LogUtils.d("app","autostart  settingCode:"+settingCode);
                    if (result != null)
                    {
                        RP_Installed_Apps rp = RP_Installed_Apps.parseJObject(result, RP_Installed_Apps.class);
                        if (rp.error_code == 0 && rp.resource != null
                                && rp.resource.total_count > 0) {
                            LogUtils.d("app", "autostart  sizie:" + rp.resource.total_count);
                            boolean isLauncherShow = true;
                            boolean isGameShow = true;
                            String launcher_entry = SkyGeneralProperties.getProperty("x_launcher_entry");
                            if (launcher_entry != null) {
                                isLauncherShow = Boolean.parseBoolean(launcher_entry);
                            } else {
                                isLauncherShow = true;
                            }
                            String gamecenter_entry = SkyGeneralProperties.getProperty("x_gamecenter_entry");
                            if (gamecenter_entry != null) {
                                isGameShow = Boolean.parseBoolean(gamecenter_entry);
                            } else {
                                isGameShow = true;
                            }
                            LogUtils.d("show", "222  isLauncherShow:" + isLauncherShow + " isGameShow:" + isGameShow);
                            for (AppData item : rp.resource.resource_items) {
                                if (currentItem != null
                                        && currentItem.pkgname.equals(item.info.pkgName)
                                        && currentItem.activity.equals(item.info.mainActivity)) {
                                    continue;
                                }

                                if (item.info.activityList != null && item.info.activityList.size() > 1) {
                                    List<MActivityInfo> mList = item.info.activityList;
                                    for (MActivityInfo aInfo : mList) {
                                        LogUtils.d("app", "autostart  pkg:" + item.info.pkgName + " name:" + aInfo.name);
                                        SkyListAppData appInfo = new SkyListAppData(ListType.LOCAL_APP_LIST,
                                                "", aInfo.name, "", item.info.pkgName);
                                        appInfo.setVersionName(String.valueOf(item.info.versionCode));
                                        appInfo.setInstallTime(item.info.firstInstallTime);
                                        appInfo.setMainActivity(aInfo.className);
                                        appInfo.setPackageName(item.info.pkgName);
                                        if (item.info.pkgName.equals("com.tianci.appstore")) {
                                            if (aInfo.className.equals(EasyLauncherActivity.class.getName())) {
                                                if (isLauncherShow)
                                                    appDatas.add(0, appInfo);
                                            } else if (aInfo.className.equals(GameMainActivity.class.getName())) {
                                                if (isGameShow)
                                                    appDatas.add(0, appInfo);
                                            } else if (aInfo.className.equals(AppStoreActivity.class.getName())) {
                                                appDatas.add(0, appInfo);
                                            }
                                        } else {
                                            if (aInfo.name != null && !aInfo.name.equals(""))
                                                appDatas.add(appInfo);
                                        }
                                    }
                                } else
                                {
                                    if(settingCode >= 21 && (item.info.pkgName.equals("com.coocaa.homeshell")
                                            || item.info.pkgName.equals("com.tianci.verysamplehome")
                                            || item.info.pkgName.equals("com.skyworth.simplehomepage")))
                                        continue;
                                    LogUtils.d("app","autostart 22 pkg:"+item.info.pkgName);
                                    SkyListAppData appInfo = new SkyListAppData(ListType.LOCAL_APP_LIST, "",
                                            item.info.appName, "", item.info.pkgName);
                                    appInfo.setVersionName(String.valueOf(item.info.versionCode));
                                    appInfo.setInstallTime(item.info.firstInstallTime);
                                    appInfo.setMainActivity(item.info.mainActivity);
                                    appInfo.setPackageName(item.info.pkgName);
                                    // if (!info.mainActivity.equals(AppStoreActivity.class.getName()))
                                    appDatas.add(appInfo);
                                }
//                                SkyListAppData appData = new SkyListAppData("", item.label, "", "",
//                                        item.pkgname);
//                                appData.setMainActivity(item.activity);
//                                appDatas.add(appData);
                            }
                        }
                    }
                    SkyListAppData appData = getHomeShellData();
                    if(appData != null && settingCode < 21)
                        appDatas.add(0, appData);
                    appDatas.add(0, empty);
                    Message msg = mainHandler.obtainMessage(UPDATE_LIST);
                    msg.obj = appDatas;
                    mainHandler.sendMessage(msg);
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    private SkyListAppData getHomeShellData() {
        PackageManager pm = mContext.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.setPackage(HOMEPKG);
        List<ResolveInfo> resolveInfo = pm.queryIntentActivities(intent, PackageManager.GET_RESOLVED_FILTER);
        if (resolveInfo != null && resolveInfo.size() > 0) {
            LogUtils.d("app", "getHomeShellData   pkg:" + HOMEPKG);
            ResolveInfo info = resolveInfo.get(0);
            String appName = info.loadLabel(mContext.getPackageManager()).toString();
            String mainActivity = info.activityInfo.name;

            SkyListAppData appInfo = new SkyListAppData(ListType.LOCAL_APP_LIST, "",
                    appName, "", HOMEPKG);
            appInfo.setMainActivity(mainActivity);
            return appInfo;
        }
        return null;
    }

    @Override
    public void onBlockClicked(View v, SkyListAppData data, int index) {
        ((Activity) mContext).finish();
    }

    @Override
    public void destroyController() {
        super.destroyController();
    }

    protected void initFlipper() {
        int row = 3, column = 4;
        listFlipper = new ListFlipper(mContext, Direction.HORIZONTAL);
        mController = new ManageListController(mContext, listFlipper, row, column);
        List<BlockData> blockDataList = createListBlockData(row, column);
        for (int i = 0; i < ListFlipper.VIEW_PAGE_COUNT; i++) {
            SkyCustomLayout page = new SkyCustomLayout(mContext, CoocaaApplication.mDiv);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            page.setLayoutParams(params);
            CustomLayoutParams netAppParams = new CustomLayoutParams();
            netAppParams.mRow = row;
            netAppParams.mCol = column;
            netAppParams.mBlockWidth = SkyConstants.Div(472);
            netAppParams.mBlockHeight = SkyConstants.Div(280);
            netAppParams.mHorizontalSpace = SkyConstants.Div(-47);
            netAppParams.mVerticalSpace = SkyConstants.Div(-36);
            netAppParams.mMarginTop = SkyConstants.Div(188);
            netAppParams.mMarginLeft = SkyConstants.Div(97);
            page.setCustomLayoutParams(netAppParams);
            page.setBlockDatas(blockDataList);
            SkyListAdapter mAdapter = new SkyListAdapter(mContext, listType, i, CoocaaApplication.mDiv);
            mAdapter.setKeyListener(mController);
            mAdapter.setOnItemClickListener(this);
            mAdapter.setMultiSelectListener(mController);
            mAdapter.setItemSelectableListener(this);
            page.setAdapter(mAdapter);
            listFlipper.addView(page);
        }
        contentLayout.addView(listFlipper, new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.MATCH_PARENT, Gravity.CENTER_VERTICAL));
    }

    private Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_LIST:
                    updateLaunchAppList((List<SkyListAppData>) msg.obj);
                    break;
                case UPDATE_STATUS:
                    refreshAppLaunchStatus((SkyListSwitchData) msg.obj);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public void updateLaunchAppList(List<SkyListAppData> dataList) {
        // TODO Auto-generated method stub
        if (dataList == null || dataList.size() == 0) {
            setEmptyTipVisible(true, mContext.getResources().getString(R.string.no_uninstall_task));
            return;
        }

        setLoadingVisible(false);
        setEmptyTipVisible(false, null);
        mController.setDataList(dataList);
        resetFocus();
    }

    public void refreshAppLaunchStatus(SkyListSwitchData data) {
        // TODO Auto-generated method stub
        for (int i = 0; i < ListFlipper.VIEW_PAGE_COUNT; i++) {
            SkyCustomLayout child = (SkyCustomLayout) listFlipper.getChildAt(i);
            for (View view : child.getChildViews()) {
                ListSwitchBlock block = (ListSwitchBlock) view;
                if (block.getPkgName() != null && block.getPkgName().equals(data.getPkgName())) {
                    block.update(data);
                    break;
                }
            }
        }
    }
}
